package com.cxlin.cwanandroid.ui.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.cxlin.base.model.api.Result
import com.cxlin.cwanandroid.model.bean.ArticleList
import com.cxlin.cwanandroid.model.repository.SquareRepository
import kotlinx.coroutines.launch
import com.cxlin.base.BaseViewModel
import com.cxlin.base.mvi.UiEvent
import com.cxlin.base.mvi.UiIntent
import com.cxlin.base.mvi.UiState
import kotlinx.coroutines.flow.update

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/30 10:04
 */
class SquareViewModel(private val repository: SquareRepository) : BaseViewModel() {

    sealed class SquareUiState : UiState {
        object Init : SquareUiState()
        data class IsRefresh(val isRefresh: Boolean) : SquareUiState()
        data class FetchArticlesSuccess(val articles: ArticleList?) : SquareUiState()
    }

    sealed class SquareEvent : UiEvent {
        class ToastEvent(val message: String, val short: Boolean = false) : SquareEvent()
    }

    sealed class SquareUiIntent : UiIntent {
        data class GetArticleList(val isRefresh: Boolean = false) : SquareUiIntent()
    }

    private var currentPage = 0

    override fun handleIntent(intent: UiIntent) {
        when (intent) {
            is SquareUiIntent.GetArticleList -> {
                viewModelScope.launch {
                    kotlin.runCatching {
                        if (intent.isRefresh) {
                            currentPage = 0
                            mUiStateFlow.update {
                                SquareUiState.IsRefresh(true)
                            }
                        }
                        val result = repository.getSquareArticleList(currentPage)
                        if (result is Result.Success) {
                            mUiStateFlow.update {
                                SquareUiState.IsRefresh(false)
                            }
                            mUiStateFlow.update {
                                SquareUiState.FetchArticlesSuccess(result.data)
                            }
                            currentPage += 1
                        } else if (result is Result.Error) {
                            mUiStateFlow.update {
                                SquareUiState.IsRefresh(false)
                            }
                            mEffectFlow.emit(
                                SquareEvent.ToastEvent(
                                    result.exception.message ?: "网络异常", true
                                )
                            )
                        }
                    }
                }
            }
        }
    }

    override fun createInitState(): UiState {
        return SquareUiState.Init
    }

}